package com.zoewin.zephyr.reportjasper.factory.creator;

import com.zoewin.zephyr.reportjasper.config.JasperConfig;
import com.zoewin.zephyr.reportjasper.entity.ReportEntity;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import java.io.File;

/**
 * Created by WQL on 2019/12/18
 * CEASE TO STRUGGLE AND YOU CEASE TO LIVE
 */
public class JasperReportCreator {

    public static ReportEntity createJasperReportByJrxml(JasperConfig config) throws Exception {
        try {
            //根据xml加载模板
            JasperDesign design = JRXmlLoader.load(config.getJrxmlPath());
            JasperReport report = JasperCompileManager.compileReport(design);
            ReportEntity reportEntity = new ReportEntity(report, config.getPicPath());
            return reportEntity;
        } catch (JRException e) {
            e.printStackTrace();
            throw new Exception("加载模板: "+config.getJrxmlPath()+" 失败, 失败原因: "+e.toString());
        }
    }

    public static ReportEntity createJasperReportByInputStream(JasperConfig config) throws Exception {
        try {
            //根据流加载模板
            JasperDesign design = JRXmlLoader.load(config.getInputStream());
            JasperReport report = JasperCompileManager.compileReport(design);
            ReportEntity reportEntity = new ReportEntity(report, config.getPicPath());
            return reportEntity;
        } catch (JRException e) {
            throw new Exception("通过流加载模板失败, 失败原因: "+e.toString());
        }
    }

    public static ReportEntity createJasperReportByJasper(JasperConfig config) throws Exception {
        try {
            JasperReport report = (JasperReport)JRLoader.loadObject(new File(config.getJasperPath()));
            ReportEntity reportEntity = new ReportEntity(report, config.getPicPath());
            return reportEntity;
        } catch (JRException e) {
            e.printStackTrace();
            throw new Exception("加载编译文件: "+config.getJrxmlPath()+" 失败, 失败原因: "+e.toString());
        }
    }

}
